package com.hkbigdata.worldcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;


/**
 * @author liuanbo
 * @creat 2023-02-28-14:25
 * @see 2194550857@qq.com
 */
public class Flink01_WordCount_Batch {
    public static void main(String[] args) throws Exception {
        //1.创建批执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //2.读取数据
        DataSource<String> source = env.readTextFile("input/word.txt");
        //3.拍平
        FlatMapOperator<String, String> word = source.flatMap(new MyFlatMap());
        //4.将单词转换为Tuple二元祖(hello,1),(spark,1)
        MapOperator<String, Tuple2<String, Integer>> wordToOneDS = word.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return new Tuple2<>(value, 1);
            }
        });
/*        MapOperator<String, Tuple2<String, Integer>> wordToOneDS = word.map((MapFunction<String, Tuple2<String, Integer>>) value -> {
            return new Tuple2<>(value, 1);
            //return Tuple2.of(value, 1);
        }).returns(Types.TUPLE(Types.STRING, Types.INT));*/
        //5.分组
        UnsortedGrouping<Tuple2<String, Integer>> groupBy = wordToOneDS.groupBy(0);
        //6.聚合
        AggregateOperator<Tuple2<String, Integer>> sum = groupBy.sum(1);

        sum.print();

        env.execute();

    }

    //实现抽象类，重写抽样方法
    public static class MyFlatMap implements FlatMapFunction<String, String> {
        @Override
        public void flatMap(String value, Collector<String> out) throws Exception {
            String[] words = value.split(" ");
            for (String word : words) {
                out.collect(word);
            }
        }
    }
}
